// pages/category/category.js
Page({
  data: {
    categoriesList: [],
    selectedCategoryProducts: [],
    selectedCategoryId: null,
  },
  onProductTap: function(event) {
    const cid = event.currentTarget.dataset.cid; 
    console.log('onProductTap cid:', cid);  
    wx.navigateTo({
      url: `/pages/goodlist/goodlist?cid=${cid}`
    });
  },
  onLoad: function() {
    this.getCategoiesData();
  },
  getCategoiesData: function() {
    var that = this;
    wx.request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/categories',
      method: 'GET',
      success: function(res) {
        if (res.data.meta.status === 200) {
          that.setData({
            categoriesList: res.data.message
          },function(){
            if (that.data.categoriesList.length > 0) {
              const firstCategoryId = that.data.categoriesList[0].cat_id;
              that.onCategoryTap({currentTarget: {dataset: {cat_id: firstCategoryId}}});
            }  
          });
        }
      }
    });
  },
  onCategoryTap: function(e) {
    const cat_id = e.currentTarget.dataset.cat_id;
    const categories = this.data.categoriesList;
    const products = this.getCategoryProducts(categories, cat_id);
    this.setData({
      selectedCategoryProducts: products,
      selectedCategoryId: cat_id
    });
  },

  getCategoryProducts: function(categories, cat_id) {
    let products = [];

    function findProducts(categoryList, id) {
      categoryList.forEach(category => {

        if (category.cat_id === id) {

          if (category.children && category.children.length > 0) {
            findProducts(category.children, id);
          }
        }

        if (category.cat_pid === id) {
          products.push({
            cat_id: category.cat_id,
            cat_name: category.cat_name,
            cat_icon: category.cat_icon
          });

          if (category.children && category.children.length > 0) {
            findProducts(category.children, category.cat_id);
          }
        }
      });
    }

    findProducts(categories, cat_id);
    return products;
  },
  goToSearchPage: function() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  }
});